/**
 * 报表设计公司(2011)
 */
package com.reportgear.swing.util;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Window;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Enumeration;
import javax.imageio.ImageIO;
import javax.swing.DefaultListModel;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JSpinner;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import javax.swing.plaf.FontUIResource;
import com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel;

/**
 * GUI实用类
 * 
 * @version 1.0 2011-3-14
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since ANNCSR 2.0
 * 
 */
public class GuiUtils {
	/**
	 * 设子窗体居中显示
	 * 
	 * @param window
	 *            窗体
	 */
	public static void centerWindow(Window window) {
		Toolkit kit = Toolkit.getDefaultToolkit();
		Dimension screenSize = kit.getScreenSize();

		window.setLocation((screenSize.width - window.getWidth()) / 2, (screenSize.height - window.getHeight()) / 2);
	}

	/**
	 * 获取系统所有字体列表
	 * 
	 * @return 系统所有字体列表
	 */
	public static String[] getAllFontNames() {
		return GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
	}

	/**
	 * 获取图像
	 * 
	 * @param fileName
	 *            图像文件名
	 * @return 图像对象
	 * @throws IOException
	 *             IO异常
	 */
	public static Image getImage(String fileName) throws IOException {
		try {
			return ImageIO.read(new URL(fileName));
		} catch (MalformedURLException ex) {
			throw ex;
		} catch (IOException ex) {
			throw ex;
		}
	}

	/**
	 * 新建空白矩形区域
	 * 
	 * @return 空白矩形区域
	 */
	public static Rectangle newEmptyRectangle() {
		return new Rectangle(0, 0, 0, 0);
	}

	/**
	 * 新建新空白点
	 * 
	 * @return 空白点
	 */
	public static Point newEmptyPoint() {
		return new Point(0, 0);
	}

	/**
	 * 设置视感
	 */
	public static void setupLookAndFeel() {
		try {
			UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (UnsupportedLookAndFeelException e) {
			e.printStackTrace();
		}
		// LookAndFeelFactory.installDefaultLookAndFeelAndExtension();
		// LookAndFeelFactory.installJideExtension(LookAndFeelFactory.OFFICE2003_STYLE);
	}

	/**
	 * 设置应用默认字体
	 * 
	 * @param fontName
	 *            字体名称
	 * @param size
	 *            字体大小
	 */
	public static void setDefaultUIFont(String fontName, int size) {
		Font font = new Font(fontName, Font.PLAIN, size);

		@SuppressWarnings("unchecked")
		Enumeration keys = UIManager.getDefaults().keys();
		while (keys.hasMoreElements()) {
			Object key = keys.nextElement();
			Object value = UIManager.get(key);
			if (value instanceof FontUIResource) {
				UIManager.put(key, font);
			}
		}
	}

	/**
	 * 设置应用默认字体，字体大小为12
	 * 
	 * @param fontName
	 *            字体名称
	 */
	public static void setDefaultUIFont(String fontName) {
		setDefaultUIFont(fontName, 12);
	}

	/**
	 * 显示弹出菜单
	 * 
	 * @param popupMenu
	 *            弹出菜单
	 * @param component
	 *            控件
	 * @param x
	 *            x
	 * @param y
	 *            y
	 */
	public static void showPopupMenu(JPopupMenu popupMenu, Component component, int x, int y) {
		if (popupMenu == null) {
			return;
		}
		Point p = new Point(x, y);
		SwingUtilities.convertPointToScreen(p, component);
		Dimension dim1 = popupMenu.getPreferredSize();
		Dimension dim2 = Toolkit.getDefaultToolkit().getScreenSize();
		dim2.setSize(dim2.getSize().width, dim2.height - 28);
		if ((p.x + dim1.width > dim2.width) && (dim1.width < dim2.width)) {
			x += dim2.width - p.x - dim1.width;
		}
		if ((p.y + dim1.height > dim2.height) && (dim1.height < dim2.height)) {
			y -= dim1.height;
		}
		popupMenu.show(component, x, y);
	}

	public static JPanel createFlowPane(Component c, int align) {
		return createFlowPane(new Component[] { c }, align);
	}

	public static JPanel createFlowPane(Component[] components, int align) {
		return createFlowPane(components, align, 0);
	}

	public static JPanel createFlowPane(Component[] components, int align, int hgap) {
		JPanel pane = new JPanel();
		pane.setLayout(new FlowLayout(align, hgap, 0));
		for (int i = 0; i < components.length; ++i) {
			pane.add(components[i]);
		}
		return pane;
	}

	/**
	 * 移除列表选择集
	 * 
	 * @param list
	 *            列表
	 * @return
	 */
	public static boolean removeJListSelectedNodes(JList list) {
		if (list.getSelectedIndex() == -1) {
			return false;
		}

		int result = JOptionPane.showConfirmDialog(SwingUtilities.getWindowAncestor(list), "确认删除选择项?", "移除",
				JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

		if (result == JOptionPane.YES_OPTION) {
			int minIndex = list.getMinSelectionIndex();
			int[] selectedIndexs = list.getSelectedIndices();
			Arrays.sort(selectedIndexs);

			for (int i = selectedIndexs.length - 1; i >= 0; --i) {
				((DefaultListModel) list.getModel()).remove(selectedIndexs[i]);
			}

			if (list.getModel().getSize() > 0) {
				if (minIndex < list.getModel().getSize()) {
					list.setSelectedValue(list.getModel().getElementAt(minIndex), true);
				} else {
					list.setSelectedValue(list.getModel().getElementAt(list.getModel().getSize() - 1), true);
				}
			}

			return true;
		}
		return false;
	}

	/**
	 * 获取Spinner控件的编辑器齐
	 * 
	 * @param spinner
	 *            Spinner控件
	 * @return
	 */
	public static JFormattedTextField getSpinnerTextField(JSpinner spinner) {
		JComponent c = spinner.getEditor();
		if (c instanceof JSpinner.DefaultEditor) {
			return ((JSpinner.DefaultEditor) c).getTextField();
		}

		return null;
	}

	/**
	 * 设置Spinner控件的列数
	 * 
	 * @param spinner
	 *            控件
	 * @param columns
	 *            列数
	 */
	public static void setColumnForSpinner(JSpinner spinner, int columns) {
		JFormattedTextField ftf = getSpinnerTextField(spinner);
		if (ftf == null) {
			return;
		}
		ftf.setColumns(columns);
		ftf.setHorizontalAlignment(2);
	}

	public static void setEnabled(JComponent component, boolean enable) {
		Border border = component.getBorder();
		if ((border != null) && (border instanceof TitledBorder)) {
			TitledBorder titleBorder = (TitledBorder) border;
			if (enable)
				titleBorder.setTitleColor(UIManager.getColor("Label.foreground"));
			else
				titleBorder.setTitleColor(UIManager.getColor("Label.disabledForeground"));
		}

		for (Component c : component.getComponents()) {
			if (c instanceof JComponent) {
				setEnabled((JComponent) c, enable);
			} else {
				c.setEnabled(enable);
			}
		}
		component.setEnabled(enable);
	}

	/**
	 * @return 标题边框颜色
	 */
	public static Color getTitleLineBorderColor() {
		Border border = UIManager.getBorder("TitledBorder.border");
		if (border instanceof LineBorder)
			return ((LineBorder) border).getLineColor();

		return Color.GRAY;
	}
}
